用二分法解方程,求在[-10,10]之间的解 2*x^3-4*x^2+3*x-6=0用c++该如何编写?

来源:百度知道 编辑:UC知道 时间:2024/06/05 18:47:26
我的积分不多,不过我真的希望大家能帮帮我!

#include <stdio.h>
#include <math.h>

typedef double (*Fun)(double);

int sign(double x)
{
return x > 0.0 ? 1 : x < 0.0 ? -1 : 0;
}

double bisection(double a, double b, Fun f) //二分法
{
double m, fa, fb, fm;
fa = f(a); fb = f(b);
if(sign(fa) == sign(fb))
{
printf("error\n");
return 0.0;
}
while(fabs(b - a) > 1e-12)
{
m = a + (b - a) * 0.5;
fm = f(m);
if(sign(fa) == sign(fm))
{
a = m;
fa = fm;
}
else
{
b = m;
fb = fm;
}
}
return m;
}

double secant (double x0, double x1, Fun f) //割线法
{
double f0, f1, x2;
f0 = f(x0); f1 = f(x1);
x2 = x1 - f1 * (x1 - x0) / (f1 - f0);
while(fabs(x2 - x1) > 1e-12)
{
x0 = x1, f0 = f1;
x1 = x2, f1 = f(x1);
x2 = x1 -